/*
 * Copyright 2013 meichenhui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.zet.tool.pluginanalyzer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipException;

import org.eclipse.osgi.util.ManifestElement;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;

/**
 * @author meichenhui
 *
 */
public class Util {
    
    public static Manifest readJarManifest(String jarPath){
        try {
            JarFile inputJar = new JarFile(jarPath);
            return inputJar.getManifest();
        } catch (IOException e) {
            throw new JarNotFoundMessage(e,jarPath);
        }
    }
    
    public static ManifestElement[] selectRequireBundles(Manifest manifest){
        try {
            return ManifestElement.parseHeader(Constants.REQUIRE_BUNDLE, manifest.getMainAttributes().getValue(Constants.REQUIRE_BUNDLE));
        } catch (BundleException e) {
            throw new InvalidHeaderValueMessage(e);
        }
    }
    
    public static SimpleBundleDescription createBundleDescription(Manifest manifest) throws ManifestNotFoundException {
        if (manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME) == null){
            throw new ManifestNotFoundException(manifest.toString());
        }
        return new SimpleBundleDescription(manifest);
    }
    
    public static SimpleBundleDescription createBundleDescription(String jarPath) throws ManifestNotFoundException {
        Manifest manifest = Util.readJarManifest(jarPath);
        if (manifest == null){
            throw new ManifestNotFoundException(jarPath);
        }
        return Util.createBundleDescription(manifest);
    }
}
